package com.sicheng.algorithm.node;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/10/6 16:06
 */

@SuppressWarnings("unused")
public class AddTowNumbers {
    public static void main(String[] args) {

        ListNode l1 = ListNode.initList(new int[]{9, 9, 9});

        ListNode l2 = ListNode.initList(new int[]{9, 9, 9, 9, 9});

        ListNode listNode = addTwoNumbers(l1, l2);
        ListNode.list(listNode);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;

        ListNode head = l1;
        //此后l1,l2均有元素
        int carry = 0;//进位
        while (l1.next != null && l2.next != null) {
            int sum = l1.val + l2.val + carry;
            if (sum < 10) {
                carry = 0;
                l1.val = sum;
            } else {
                carry = 1;
                l1.val = sum - 10;
            }

            l1 = l1.next;
            l2 = l2.next;
        }


        int sum = l1.val + l2.val + carry;
        if (sum < 10) {
            carry = 0;
            l1.val = sum;
        } else {
            carry = 1;
            l1.val = sum - 10;
        }

        if (l1.next == null) {
            l1.next = l2.next;
        }

        while (l1.next != null) {
            l1 = l1.next;
            sum = carry + l1.val;
            if (sum < 10) {
                l1.val = sum;
                carry = 0;
                break;
            } else {
                l1.val = sum - 10;
                carry = 1;
            }
        }

        if (carry != 0) {
            l1.next = new ListNode(carry);

        }


        return head;

    }
}
